package com.example.yskjproject.view.dialog;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.media.metrics.Event;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.yskjproject.R;
import com.example.yskjproject.adapter.PicVideoAdapter;
import com.example.yskjproject.content.Content;
import com.example.yskjproject.content.EventContent;
import com.example.yskjproject.event.EventMessage;
import com.example.yskjproject.http.APIService;
import com.example.yskjproject.http.Urls;
import com.example.yskjproject.http.callback.JsonCallback;
import com.example.yskjproject.model.BooleanLoginWorksModel;
import com.example.yskjproject.model.FollowModel;
import com.example.yskjproject.model.LzyResponse;
import com.example.yskjproject.model.RoomLiveInfoModel;
import com.example.yskjproject.model.RoomOneLiveInfoModel;
import com.example.yskjproject.model.WorkInfoModel;
import com.example.yskjproject.ui.activity.ClassroomWorksActivity;
import com.example.yskjproject.utils.EventBusUtil;
import com.example.yskjproject.utils.GenerateTestUserSig;
import com.example.yskjproject.utils.Log;
import com.example.yskjproject.utils.LogUtils;
import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.tencent.qcloud.tuicore.TUILogin;
import com.tencent.qcloud.tuicore.interfaces.TUICallback;
import com.tencent.qcloud.tuicore.util.ToastUtil;
import com.xzh.imagepicker.bean.MediaFile;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import es.dmoral.toasty.Toasty;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * WorkDialogHelper  用户进入工作室
 * <p>
 * 作者：zx
 * 创建时间：2024/4/24
 */
public class LoginWorkDialogHelper extends Dialog {

    public static int REQUEST_SELECT_IMAGES_CODE = 0x01;

    private Context context;

    private AppCompatImageView disSelectImg;
    private VideoView videoView;
    private AppCompatImageView videoBg;
    private RelativeLayout videoLayout;

    private AppCompatImageButton startVideo;
    private RecyclerView rvPicVideo;

    private Gson gson = new Gson();
    private AppCompatTextView tvName, tvIntroduction, tvJlName, tvKcName, tvKcType, tvKcState, tvKcIntroduce, tvKcTime, tvKcMoney;

    private AppCompatButton btnLogin;

    private AppCompatImageView imgFollow;
    private List<MediaFile> listMedia = Lists.newArrayList();
    private PicVideoAdapter picVideoAdapter;

    private int studioId;


    public LoginWorkDialogHelper(@NonNull Context context, int studioId) {
        super(context);
        this.context = context;
        setContentView(R.layout.login_works_dialog);
        this.studioId = studioId;
    }

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        int layoutWidth;
        int layoutHeight;
        if (window != null) {
            DisplayMetrics displayMetrics = new DisplayMetrics();
            ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int screenWidth = displayMetrics.widthPixels;
            int screenHeight = displayMetrics.heightPixels;
            // 打印尺寸
            LogUtils.d("ScreenSize" + "Width: " + screenWidth + ", Height: " + screenHeight);
            if (screenWidth > 3000) {
                layoutWidth = (int) (screenWidth * 0.5f);
                layoutHeight = (int) (screenHeight * 0.65f); // 保持原始宽高比
            } else {
                layoutWidth = (int) (screenWidth * 0.9f);
                layoutHeight = (int) (screenHeight * 0.4f);
            }
            WindowManager.LayoutParams layoutParams = window.getAttributes();
            layoutParams.width = layoutWidth;
            layoutParams.height = layoutHeight;
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.setAttributes(layoutParams);
        }
        setCanceledOnTouchOutside(false);
        setDateInfo();
    }

    /**
     * 设置我的工作室内容
     */
    @SuppressLint("NotifyDataSetChanged")
    private void setDateInfo() {
        findViewById(R.id.img_colose).setOnClickListener(dis -> dismiss());
        disSelectImg = findViewById(R.id.dis_select_img);
        videoView = (VideoView) findViewById(R.id.video_view);
        videoBg = findViewById(R.id.video_bg);
        videoLayout = findViewById(R.id.video_layout);
        startVideo = findViewById(R.id.start_video);

        imgFollow = findViewById(R.id.img_follow);
        //name
        tvName = findViewById(R.id.tv_name);
        //简介
        tvIntroduction = findViewById(R.id.tv_introduction);
        tvJlName = findViewById(R.id.tv_jl_name);
        tvKcName = findViewById(R.id.tv_kc_name);
        tvKcType = findViewById(R.id.tv_kc_type);
        //课程状态
        tvKcState = findViewById(R.id.tv_kc_state);
        tvKcIntroduce = findViewById(R.id.tv_kc_introduce);
        tvKcTime = findViewById(R.id.tv_kc_time);
        tvKcMoney = findViewById(R.id.tv_kc_money);
        btnLogin = findViewById(R.id.btn_login_works);
        btnLogin.setOnClickListener(next -> getNextWorks(studioId));

        imgFollow.setOnClickListener(follow -> {
            //点赞
            new Thread(() -> {
                Map<String, Object> jsonParams = new HashMap<>();
                jsonParams.put("studio_id", studioId);
                String paramsDate = gson.toJson(jsonParams);
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramsDate);
                OkGo.<LzyResponse<FollowModel>>post(Urls.FOLLOW).upRequestBody(requestBody).execute(new JsonCallback<LzyResponse<FollowModel>>() {
                    @SuppressLint({"SimpleDateFormat", "NewApi", "UseCompatLoadingForDrawables"})
                    @Override
                    public void onSuccess(Response<LzyResponse<FollowModel>> response) {
                        FollowModel.FollowInfoBean followModel = response.body().data.getFollow_info();
                        if (followModel != null) {
                            if (followModel.getState() == 1) {
                                imgFollow.setBackground(context.getDrawable(R.drawable.love_icon));
                            } else {
                                imgFollow.setBackground(context.getDrawable(R.drawable.love_gray_icon));
                            }
                            EventBusUtil.sendEvent(new EventMessage(EventContent.updateState));
                        }
                    }

                    @SuppressLint("CheckResult")
                    @Override
                    public void onError(Response<LzyResponse<FollowModel>> response) {
                        super.onError(response);
                        ToastUtil.toastShortMessage("点赞失败");
                    }
                });
            }).start();

        });

        rvPicVideo = findViewById(R.id.rv_pic_video);
        rvPicVideo.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false));
        picVideoAdapter = new PicVideoAdapter(listMedia, context, "other");
        rvPicVideo.setAdapter(picVideoAdapter);
        getWorksInfo();
        picVideoAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @SuppressLint({"NewApi", "ResourceType"})
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.delect_img) {
                    listMedia.remove(position);
                    if (!listMedia.isEmpty()) {
                        Glide.with(context).load(listMedia.get(0).getPath())
                                .apply(RequestOptions.bitmapTransform(new RoundedCorners(10)))//圆角半径
                                .into(disSelectImg);
                    } else {
                        Glide.with(context).load(context.getColor(R.color.white))//圆角半径
                                .apply(RequestOptions.bitmapTransform(new RoundedCorners(10)))//圆角半径
                                .into(disSelectImg);
                    }
                } else if (view.getId() == R.id.item_pic_video) {
                    if (!listMedia.isEmpty()) {
                        if (listMedia.get(position).getFolderName().equals("picture") || listMedia.get(position).getFolderName().equals("Pictures")) {
                            disSelectImg.setVisibility(View.VISIBLE);
                            videoView.setVisibility(View.GONE);
                            Glide.with(context).load(listMedia.get(position).getPath())//圆角半径
                                    .into(disSelectImg);
                        } else if (listMedia.get(position).getFolderName().equals("video") || listMedia.get(position).getFolderName().equals("Movies")) {
                            disSelectImg.setVisibility(View.GONE);
                            videoLayout.setVisibility(View.VISIBLE);
                            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                            try {
                                retriever.setDataSource(listMedia.get(position).getPath()); // videoPath 是视频文件的路径
                                Bitmap firstFrame = retriever.getFrameAtTime(0);
                                Glide.with(context).load(firstFrame)
                                        .apply(RequestOptions.bitmapTransform(new RoundedCorners(40)))//圆角半径
                                        .into(videoBg);
                            } catch (IllegalArgumentException e) {
                                e.printStackTrace();
                            } finally {
                                try {
                                    retriever.release();
                                } catch (IOException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                            videoView.setVideoPath(listMedia.get(position).getPath());
                        }
                    }
                }
                picVideoAdapter.notifyDataSetChanged();
            }
        });

        startVideo.setOnClickListener(start -> {
            videoBg.setVisibility(View.GONE);
            videoView.start();
        });


    }

    /**
     * 验证是否能进入工作室
     */
    private void getNextWorks(int studio_id) {
        Type type = new TypeToken<LzyResponse<BooleanLoginWorksModel>>() {
        }.getType();
        APIService.<LzyResponse<BooleanLoginWorksModel>>getData(type, Urls.CHECK_JOIN + "?studio_id=" + studio_id).subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<BooleanLoginWorksModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("onSubscribe ： " + d);
            }

            @SuppressLint({"NotifyDataSetChanged", "UseRequireInsteadOfGet", "CheckResult"})
            @Override
            public void onNext(BooleanLoginWorksModel booleanLoginWorksModel) {
                if (booleanLoginWorksModel == null) {
                    return;
                }
                if (booleanLoginWorksModel.isJoin_enable()) {
                    // todo 可以的进去的逻辑   roomId
                    nextLoginZB(studio_id, booleanLoginWorksModel.getMsg());
                } else {
                    // 不可以进去的逻辑
                    ToastUtil.toastShortMessage(booleanLoginWorksModel.getMsg());
                }
            }


            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取失败");
            }

            @Override
            public void onComplete() {

            }
        }); //

    }

    private void nextLoginZB(int studioId, String msg) {
        OkGo.<LzyResponse<RoomLiveInfoModel>>get(Urls.LIVE_INFO + "?studio_id=" + studioId).execute(new JsonCallback<LzyResponse<RoomLiveInfoModel>>() {
            @Override
            public void onSuccess(Response<LzyResponse<RoomLiveInfoModel>> response) {
                RoomLiveInfoModel data = response.body().data;
                if (data == null) {
                    return;
                }
                TUILogin.login(context,
                        Content.SDK_ID,     // 请替换为步骤一取到的 SDKAppID
                        data.getLive_user_id(),        // 请替换为您的 UserID
                        GenerateTestUserSig.genTestUserSig(String.valueOf(data.getLive_user_id())),  // 您可以在控制台中计算一个 UserSig 并填在这个位置
                        new TUICallback() {
                            @Override
                            public void onSuccess() {
                                Intent intent = new Intent(context, ClassroomWorksActivity.class);
                                intent.putExtra("id", data.getLive_room_id());
                                intent.putExtra("roomName", data.getStudio_info().getTitle());
                                intent.putExtra("userName", data.getLive_user_name());
                                intent.putExtra("avatar_url", data.getAvatar_url());
                                intent.putExtra("studioWork", data.getStudio_info().getId());
                                intent.putExtra("userId", data.getLive_user_id());
                                if (data.getStudio_info().getCourse_info() != null) {
                                    intent.putExtra("courseId", data.getStudio_info().getCourse_info().getId());
                                    intent.putExtra("price", data.getStudio_info().getCourse_info().getPrice() /100 + "");
                                }
                                intent.putExtra("muteMicrophone", !true);
                                intent.putExtra("openCamera", true);
                                intent.putExtra("soundOnSpeaker", true);
                                if (msg.equals("教练本人，可进入")) {
                                    intent.putExtra("enableSeatControl", false);
                                    intent.putExtra("isCreate", true);
                                } else {
                                    intent.putExtra("isCreate", false);
                                }
                                context.startActivity(intent);
                                dismiss();
                            }

                            @SuppressLint("CheckResult")
                            @Override
                            public void onError(int errorCode, String errorMessage) {
                                ToastUtil.toastShortMessage(errorMessage);
                            }

                        });


            }

            @Override
            public void onError(Response<LzyResponse<RoomLiveInfoModel>> response) {
                super.onError(response);
            }
        });
    }


    /**
     * 获取工作室info
     */
    private void getWorksInfo() {
        Type type = new TypeToken<LzyResponse<WorkInfoModel>>() {
        }.getType();
        APIService.<LzyResponse<WorkInfoModel>>getData(type, Urls.WORK_INFO + "?studio_id=" + studioId).subscribeOn(Schedulers.io()).map(response -> response.data).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<WorkInfoModel>() {
            @Override
            public void onSubscribe(Disposable d) {
                Log.e("onSubscribe ： " + d);
            }

            @SuppressLint({"NotifyDataSetChanged", "UseRequireInsteadOfGet", "NewApi", "UseCompatLoadingForDrawables"})
            @Override
            public void onNext(WorkInfoModel leftLevel2Model) {
                if (leftLevel2Model == null) {
                    return;
                }
                tvName.setText(leftLevel2Model.getStudio_info().getTitle());
                tvIntroduction.setText(leftLevel2Model.getStudio_info().getDescription());
                tvJlName.setText(leftLevel2Model.getStudio_info().getNick_name());
                tvKcName.setText(leftLevel2Model.getStudio_info().getCourse_info().getCourse_name());
                String userZy = "";
                int userZyId;
                if (leftLevel2Model.getStudio_info().getCourse_info().getTag_lv1_id() == 1) {
                    //id  = 1
                    userZy = "私教";
                    userZyId = 1;
                } else if (leftLevel2Model.getStudio_info().getCourse_info().getTag_lv1_id() == 2) {
                    //id  = 2
                    userZy = "团课";
                    userZyId = 2;
                } else if (leftLevel2Model.getStudio_info().getCourse_info().getTag_lv1_id() == 3) {
                    //id  = 3
                    userZy = "陪练";
                    userZyId = 3;
                } else if (leftLevel2Model.getStudio_info().getCourse_info().getTag_lv1_id() == 4) {
                    //id  = 4
                    userZy = "直播";
                    userZyId = 4;
                }
                String personnelNumber = "1v" + leftLevel2Model.getStudio_info().getCourse_info().getMax_quantity();
                tvKcType.setText(userZy + "   " + personnelNumber);
                String strState = "";
                switch (leftLevel2Model.getStudio_info().getCourse_info().getState()) {
                    case 0:
                        strState = "未开课";
                        break;
                    case 1:
                        strState = "售卖中";
                        break;
                    case 2:
                        strState = "已满员";
                        break;
                    case 3:
                        strState = "上课中";
                        break;
                    case 4:
                        strState = "已下课";
                        break;
                    case -1:
                        strState = "已下线";
                        break;

                }
                tvKcState.setText(strState);
                tvKcIntroduce.setText(leftLevel2Model.getStudio_info().getCourse_info().getDescription());
                tvKcTime.setText(leftLevel2Model.getStudio_info().getCourse_info().getDuration() / 60 + "分");
                tvKcMoney.setText((float) leftLevel2Model.getStudio_info().getCourse_info().getPrice() / 100.0 + "元");
                for (WorkInfoModel.StudioInfoBean.MediaListBean bean : leftLevel2Model.getStudio_info().getMedia_list()) {
                    listMedia.add(new MediaFile(bean
                            .getMedia_url(), bean.getMedia_type()));
                    picVideoAdapter.notifyDataSetChanged();
                }
                if (!listMedia.isEmpty()) {
                    //TODO 此处加载可能是个坑，影响dialog的宽度。后期可以尝试修复
                    Glide.with(context).load(listMedia.get(0).getPath())//圆角半径
                            .apply(RequestOptions.bitmapTransform(new RoundedCorners(10)))
                            .into(disSelectImg);
                }
                if (leftLevel2Model.getStudio_info().getFollow() == 1) {
                    imgFollow.setBackground(context.getDrawable(R.drawable.love_icon));
                } else {
                    imgFollow.setBackground(context.getDrawable(R.drawable.love_gray_icon));
                }
            }

            @SuppressLint("CheckResult")
            @Override
            public void onError(Throwable e) {
                e.printStackTrace();            //请求失败
                Log.e("onError ： " + "获取失败");
                Toast.makeText(context, gson.toJson(e), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete() {

            }
        }); //

    }


    @Override
    public void dismiss() {
        super.dismiss();
        if (videoView != null) {
            videoView.stopPlayback();
        }
    }

}
